<?php declare(strict_types=1);

namespace App\Util;

use App\Models\User;


class ListUtil
{

    public static function createTreeNode(array $data, int $pid = 0, string $mark = '#', int $level = 1, string $key = 'id', string $pkey = 'pid', array &$tree = []): array
    {
        foreach ($data as $k => $v) {
            if ($v[$pkey] == $pid) {
                $v["level"] = $level;
                $v['mark'] = str_repeat($mark, $level - 1);
                $tree[] = $v;
                unset($data[$k]);
                self::createTreeNode($data, $v[$key], $mark, $level + 1, $key, $pkey, $tree);
            }
        }
        return $tree;
    }

    public static function createListsNode(array $elements, int $parentId = 0, string $pkey = 'pid', string $key = 'id', int $level = 0): array
    {
        $child = [];
        foreach ($elements as $element) {
            $element["level"] = $level;
            if ($element[$pkey] == $parentId) {
                $children = self::createListsNode($elements, $element[$key], $pkey, $key, $level + 1);
//                if ($children) {
                $element['children'] = $children;
//                }
                $child[] = $element;
            }
        }
        return $child;
    }


    public static function prevGetTreeNode($nodes, array $curNode, array &$list = []): array
    {
        foreach ($nodes as $node) {
            if ($node["id"] == $curNode["id"]) {
                $list[] = $node;
                $curNode["id"] = $node["pid"];
                self::prevGetTreeNode($nodes, $curNode, $list);
            }
        }
        return $list;
    }

    /**
     * 从多个单向链表中取出节点
     * @param array $listNodes
     * @param array $node
     * @return array
     */
    public static function getListsNode(array $listNodes, array $node): array
    {
        $nodes = [];
        foreach ($listNodes as $listNode) {
            if ($listNode['id'] == $node['id']) {
                return $listNode;
            } else {
                if (!empty($listNode['children'])) {
                    $nodes = self::getListsNode($listNode['children'], $node);
                    if (!empty($nodes)) {
                        break;
                    }
                }
            }
        }
        return $nodes;
    }


    /**
     * 多个单向链表转换成数组
     */
    public static function listsNodeToArray(array $listNodes, array &$nodes = []): array
    {
        foreach ($listNodes as $listNode) {
            $topHead = $listNode;
            unset($topHead['children']);
            $nodes[] = $topHead;
            $listNodes = $listNode['children'];
            if (!empty($listNodes)) {
                $nodes = self::listsNodeToArray($listNodes, $nodes);
            }
        }
        return $nodes;
    }
}
